package com.foreknow.tijian.dao.Impl;

import com.foreknow.tijian.dao.OverallResultDao;
import com.foreknow.tijian.po.Cidetailedreport;
import com.foreknow.tijian.po.Cireport;
import com.foreknow.tijian.po.OverallResult;
import com.foreknow.tijian.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OverallResultDaoImpl implements OverallResultDao {
    @Override
    public List<OverallResult> listOverallResultByOrderId(OverallResult result) {
        //连接数据库
        Connection con= DBUtil.getConnection();
        PreparedStatement pst = null;
        List<OverallResult> list=new ArrayList<OverallResult>();
        StringBuffer sql=new StringBuffer();
        sql.append("select c.ciName cname, ");
        sql.append("b.name bname, ");
        sql.append("b.normalValueString bnomalname, ");
        sql.append("b.value bvalue, ");
        sql.append("b.unit bunit, ");
        sql.append("a.title atitle, ");
        sql.append("a.content acontent "); // 注意：若这是最后一个字段，需去掉末尾逗号
        sql.append("FROM cireport c left JOIN cidetailedreport b ON c.ciId = b.ciId ");
        sql.append("LEFT JOIN overallresult a ON a.orderId=c.orderId ");
        sql.append("where a.orderId=?");
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql.toString());
            //把问号替换
            pst.setString(1,result.getOrderId());
            ResultSet rs=pst.executeQuery();
            while(rs.next()){
                OverallResult overallResult=new OverallResult();
                overallResult.setContent(rs.getString("acontent"));
                overallResult.setTitle(rs.getString("atitle"));
                Cireport c=new Cireport();
                c.setCiName(rs.getString("cname"));
                Cidetailedreport b=new Cidetailedreport();
                b.setName(rs.getString("bname"));
                b.setNormalValueString(rs.getString("bnomalname"));
                b.setValue(rs.getString("bvalue"));
                b.setUnit(rs.getString("bunit"));
                c.setCidetailedreport(b);
                overallResult.setCireport(c);
                list.add(overallResult);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(pst);
        }
        return list;
    }
}
